-- UISkyCityTowerBonus
-- Create by choudh
-- 天空之城试练塔奖励

require "game/ui/misc/UIIndicator"
require "game/ui/form/common/UIBonusNotify"
require "game/ui/form/workshop/UIItemDesc"
require "game/ui/form/hero/UIHeroDetailInfo"

--UISkyCityTowerBonus继承自Layer
UISkyCityTowerBonus = class("UISkyCityTowerBonus", function()
    return cc.Layer:create();
end);

local campSortRule = {1, 2, 3, 4};

function UISkyCityTowerBonus.create(camp)
    return UISkyCityTowerBonus.new(camp);
end

-- 构造函数
function UISkyCityTowerBonus:ctor(camp)
    self:setName("UISkyCityTowerBonus");

    -- 初始化
    local node = cc.CSLoader:createNode("layout/talent/TalentFruitBonus.csb");
    self:addChild(node);
    self.node = node;

    self.camp = camp;

    local bonusTitleLabel = findChildByName(node, "CT/bonus_title");
    self.initY = bonusTitleLabel:getPositionY();

    self:init();

    -- 重绘
    self:redraw();

    -- 注册点击事件
    self:registerTouchEvent();

    -- 注册事件处理回调函数
    self:registerEventCallback();

    -- 适配
    self:resize();

    self:redrawTabs();
end

-- 重绘
function UISkyCityTowerBonus:redraw()
    local node = self.node;

    -- 隐藏奖励按钮
    local btnTakeBonus = findChildByName(self.node, "BT/take_bonus");
    btnTakeBonus:setVisible(false);

    -- 奖励标题
    local bonusTitleLabel = findChildByName(node, "CT/bonus_title");
    TextStyleM.setTextStyle(bonusTitleLabel, TextStyleM.TEXT_SIZE_MIDDLE2, TextStyleM.TEXT_COLOR_ORANGE, true, -4, nil, nil, nil, nil, true);

    -- 根据阵营设置标题
    bonusTitleLabel:setString(getLocStr("trial_type_" .. self.camp));
    bonusTitleLabel:setPositionY(self.initY - 15);

    -- 奖励需求
    local bonusRequireLabel = findChildByName(node, "CT/bonus_require");
    TextStyleM.setTextStyle(bonusRequireLabel, TextStyleM.TEXT_SIZE_MIDDLE2, TextStyleM.TEXT_COLOR_ORANGE, true, -4, nil, nil, nil, nil, true);

    local dirName = CampM.query(self.camp, "sky_tower_name");
    bonusRequireLabel:setString(dirName);
    bonusRequireLabel:setPositionY(self.initY - 15);
end

-- 注册点击事件
function UISkyCityTowerBonus:registerTouchEvent()
    -- 注册返回按钮点击事件
    local btnBack = findChildByName(self.node, "BT/btn_back");
    local function onBackClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            -- 关闭当前界面
            AudioM.playFx("ship_return");
            UIMgr.getCurrentScene():removeFormByName("UISkyCityTowerBonus");
        end
    end
    AddBackEventHandler(self, btnBack, onBackClick);
    TextStyleM.setTextStyle(btnBack, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    btnBack:setTitleText(getLocStr("btn_text_back"));
end

-- 注册事件处理回调函数
function UISkyCityTowerBonus:registerEventCallback()
    -- 关注领取奖励的回调
    EventMgr.register("UISkyCityTowerBonus", event.SKY_TOWER_BONUS, function(args)
        self:whenTakeBonus(args);
    end);

    -- 注册获得焦点的回调
    EventMgr.register("UISkyCityTowerBonus", event.FOCUS_CHANGED, function(para)
        -- TODO
        if para["get"] == "UISkyCityTowerBonus" then
            UIMgr:getCurrentScene().topMenu:show(TOPMENU_FRAME_MONEY, TOPMENU_FRAME_GEM, TOPMENU_FRAME_HEAD_AIRSHIP);
        elseif para["lose"] == "UISkyCityTowerBonus" then

        end
    end);

    self:registerScriptHandler(function(ev)
        if ev == "enterTransitionFinish" then
            -- 默认显示最底部内容
            local scrollview = findChildByName(self.node, "CT/scrollview");
            self:jumpTo(self.lastTaken);
        elseif ev == "exit" then
            EventMgr.removeAll("UISkyCityTowerBonus");
        elseif ev == "enter" then

        end
    end);
end

-- 初始化奖励
function UISkyCityTowerBonus:initItem(node, bonus, id)
    -- 图标
    local icon = findChildByName(node, "icon");

    local iconPath;
    local name;
    local num = bonus[3];
    local scale = 0.6;
    local offsetY = 0;

    -- 奖励名称
    local nameLabel = findChildByName(node, "name");
    TextStyleM.setTextStyle(nameLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_DARK_BROWN);

    -- 需求数量
    local numLabel = findChildByName(node, "num");
    TextStyleM.setTextStyle(numLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_DARK_BROWN);
    numLabel:setString(string.format("%dF", id));
    self.isHonorDebris = false;

    -- 如果名称超长的话，需要增加缩进
    local function getNameKerning(name)
        if string.len(name) > 30 then
            return -2;
        elseif string.len(name) > 20 then
            return -1;
        else
            return 0;
        end
    end

    if bonus[1] == 1 then
        -- 是道具， 获取道具图标
        iconPath = getItemIconPath(ItemM.query(bonus[2], "icon"));
        name = ItemM.query(bonus[2], "name");

        -- 如果是食材，设置颜色TEXT_COLOR_DARK_BROWN
        if ItemM.query(bonus[2], "group") == 20 or
           ItemM.query(bonus[2], "group") == 1 then
            TextStyleM.setTextStyle(nameLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_DARK_BROWN, false, getNameKerning(name));

            scale = 0.6;
        elseif ItemM.query(bonus[2], "group") == 21 then
              -- 神器字体颜色
            TextStyleM.setTextStyle(nameLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_BLUE, false, getNameKerning(name));

            scale = 0.6;
        elseif ItemM.query(bonus[2], "group") == 22 then
            -- 神器碎片
            TextStyleM.setTextStyle(nameLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_BLUE, false, getNameKerning(name));

            scale = 0.6;
        elseif ItemM.query(bonus[2], "group") == 17 then
            -- 荣誉碎片颜色
            TextStyleM.setTextStyle(nameLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_DARK_BROWN, false, getNameKerning(name));

            self.isHonorDebris = true;
            scale = 0.5;
        elseif ItemM.query(bonus[2], "group") == 28 then
            -- 配方颜色
            TextStyleM.setTextStyle(nameLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_DARK_BROWN, false, getNameKerning(name));

            scale = 0.6;
        end
    elseif bonus[1] == 2 then
        -- 属性
        name = FieldsM.query(bonus[2], "name");
        scale = 1;
        -- 设置萝卜和钻石颜色
        if "radish" == bonus[2] then
            name = getLocStr("life_limit");
            TextStyleM.setTextStyle(nameLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_DARK_RED, false, getNameKerning(name));
            iconPath = getLargeAttribIconPath("life");
        elseif "gem" == bonus[2] then
            TextStyleM.setTextStyle(nameLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_DARK_BROWN, false, getNameKerning(name));
            iconPath = getLargeAttribIconPath("gem_large");
        end

    elseif bonus[1] == 3 then
        -- 冈布奥
        local classId = tonumber(bonus[2]);
        local fileName = PetM.getDefaultIcon(classId);
        iconPath = getHeroIconPath(tostring(fileName));
        name = PetM.query(classId, "name");

        -- 冈布奥颜色设置为
        TextStyleM.setTextStyle(nameLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_BLUE, false, getNameKerning(name));

        scale = 0.6;
        offsetY = 6 ;

    elseif bonus[1] == 6 then
        -- 秘宝
        name = SkyShipSkillM.query(bonus[2], "name");
        scale = 0.6;

        TextStyleM.setTextStyle(nameLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_DARK_RED, false, getNameKerning(name));
        iconPath = getAirShipSkillIconPath(SkyShipSkillM.query(bonus[2], "icon"));
    end
    icon:loadTexture(iconPath);
    icon:setScale(scale);
    icon:setPositionY(icon:getPositionY()+offsetY);

    if num > 1 then
        nameLabel:setString(string.format("%s×%s", name, num));
    else
        nameLabel:setString(name);
    end

    if "radish" == bonus[2] or "gem" == bonus[2] then
       nameLabel:setString(string.format("%s+%s", name, num));
    end

    -- 点击处理
    local bg = findChildByName(node, "touch_bg");
    bg:addTouchEventListener(function(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            showBonusDesc(bonus);
        end
    end);
end

-- 更新是否已领取的标识
function UISkyCityTowerBonus:updateTakenFlag(id)
    local node = self.itemIcons[id];
    local curPorgress = SkyTowerM.getProgress(self.camp);
    local curBonusPorgress = SkyTowerM.getBonusProgress(self.camp);

    if curBonusPorgress >= id then
        self.lastTaken = id;
    end

    -- 可领取光效
    local light = findChildByName(node, "light");

    local nameLabel = findChildByName(node, "name");
    local numLabel = findChildByName(node, "num");
    local mengban  = findChildByName(node, "taken_image");
    local itemIcon = findChildByName(node, "icon");

    -- 是否可领取
    if curPorgress >= id then
        -- 是否已领取

        if curBonusPorgress >= id then
            -- 已领取，名字置灰，添加一层黄色蒙版
            mengban:setVisible(true);
            light:setVisible(false);
            itemIcon:stopAllActions();

            TextStyleM.setTextStyle(nameLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_GRAY);

            TextStyleM.setTextStyle(numLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_GRAY);
            if getLang() == "zh" or getLang() == "tw" then
                numLabel:setString(getLocStr("has_complete"));
            else
                numLabel:setString("");
            end
        else
            -- 一般走不到这里面来
            cclog(string.format("一般走不到这里面来，检查下ID：%d的奖励是否已领取", id));

            TextStyleM.setTextStyle(numLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_GREEN);
            if getLang() == "zh" or getLang() == "tw" then
                numLabel:setString(getLocStr("can_be_taken"));
            end

            light:setVisible(true);
            local rotateForever = cc.RepeatForever:create(cc.RotateBy:create(30, 360));
            light:runAction(rotateForever);

            -- 判断是不是荣誉碎片，荣誉碎片要缩放要小点
            local towerId = SkyTowerM.getTowerId(self.camp, id);
            local bonus = SkyTowerM.query(towerId, "bonus");

            if self.isHonorDebris then
                playBubbleAnima2(itemIcon, false, 0.5);
            elseif bonus[2] == "radish" then
                playBubbleAnima2(itemIcon, false, 1);
            elseif bonus[2] == "gem" then
                playBubbleAnima2(itemIcon, false, 1);
            else
                playBubbleAnima2(itemIcon, false, 0.6);
            end
        end
    else
        -- 不可领取
        light:setVisible(false);
    end
end

-- 移动中心
function UISkyCityTowerBonus:jumpTo(id)
    id = iif(id==nil, 1, id);

    id = id - 3;

    local scrollview = findChildByName(self.node, "CT/scrollview");
    local percent = id * 100 / self.totalCount;
    if percent < 0 then
        percent = 0;
    end

    scrollview:jumpToPercentVertical(percent);
end

-- 初始化奖励数据
function UISkyCityTowerBonus:initData()
    local maxFloor = SkyTowerM.getMaxFloor(self.camp);
    local data = {};

    for index = 1, maxFloor do
        local towerId = SkyTowerM.getTowerId(self.camp, index);
        local info = {["floor"] = index, ["bonus"] = SkyTowerM.getCurBonus(self.camp, index), };

        table.insert(data, info);
    end

    return data;
end

-- 初始化奖励列表
function UISkyCityTowerBonus:init()
    local scrollview = findChildByName(self.node, "CT/scrollview");
    scrollview:removeAllChildren();

    local itemNode = cc.CSLoader:createNode("layout/talent/FruitBonusItem.csb");
    local widget = replaceNodeWithWidget(itemNode);

    -- 获取奖励列表
    local bonusList = self:initData();

    -- 左边距
    local leftMargin = 1;

    -- 行间距
    local gap = 0;
    local widgetHeight = 61;

    local totalNum = #bonusList;

    self.totalCount = totalNum;

    local startHeight = 0;

    -- 计算总高度
    local totalHeight = math.max(totalNum * (widgetHeight + gap), scrollview:getInnerContainerSize().height);
    if totalHeight < scrollview:getInnerContainerSize().height then
        startHeight = scrollview:getInnerContainerSize().height - totalHeight;
    end

    scrollview:setInnerContainerSize(cc.size(scrollview:getInnerContainerSize().width, totalHeight));

    self.itemIcons = {};
    local i = 0;
    for id, info in ipairs(bonusList) do
        local bonus = info["bonus"];

        local child = widget:clone();
        local x = leftMargin;
        local y = startHeight + i * (widgetHeight + gap);
        child:setPositionX(x);
        child:setPositionY(y);

        self.itemIcons[id] = child;

        -- 初始化奖励
        child:setTag(i);
        self:initItem(child, bonus, id);
        self:updateTakenFlag(id);

        scrollview:addChild(child);
        i = i + 1;
    end

    UIIndicator.attach(scrollview);
end

-- 适配
function UISkyCityTowerBonus:resize()
    local node = self.node;

    -- bg居中显示并充满整个屏幕
    AlignM.fitToScreen(node, "bg");

    -- CT居中并缩放至合适大小
    AlignM.alignToCenter(node, "CT");

    -- BT置于底部并缩放至合适大小
    AlignM.alignToBottomCenter(node, "BT");
end

-- 领取奖励的回调
function UISkyCityTowerBonus:whenTakeBonus(args)
    local bonusList = args.bonus;

    if bonusList ~= nil and #bonusList > 0 then
        showBonusNotifyForm(getLocStr("tower_bonus"), { bonusList });
    end
end

-- 绘制标签页
function UISkyCityTowerBonus:redrawTabs()
    local tabNode = findChildByName(self.node, "CT/tab");
    tabNode:setVisible(true);

    -- 标签页
    local tabNum = CampM.getCampsCount();

    -- 先移除旧的标签
    tabNode.rows = {};
    tabNode:removeAllChildren();

    -- 根据tab数据，生成新标签
    local widget = replaceNodeWithWidget(cc.CSLoader:createNode("layout/tab/tab.csb"));

    -- 置灰颜色
    local blendColor = TextStyleM.TEXT_COLOR_BLEND;
    local normalColor = TextStyleM.TEXT_COLOR_NORMAL;

    for i = 1, tabNum do
        local child = widget:clone();
        child:setName("tab" .. i);
        child.index = i;

        self:registerTabTouchEvent(child);

        -- 计算单元格坐标
        -- 这个坐标将是单元格的描点所在
        local x = (i - 1) * 68 + 55;
        local y = 75;

        child:setPositionX(x);
        child:setPositionY(y);

        local tabLight = findChildByName(child, "light");
        local tabImage = findChildByName(child, "tab");
        tabLight:setScaleX(0.7);
        tabImage:setScaleX(0.7);

        local tabText = findChildByName(child, "text");
        local tabIcon = findChildByName(child, "icon");

        tabText:setVisible(false);

        if campSortRule[i] == self.camp then
            tabLight:setVisible(true);
            tabIcon:loadTexture(getCampSmallIconPath(campSortRule[i]));
            tabIcon:setColor(normalColor);
            tabImage:setColor(normalColor);
        else
            tabLight:setVisible(false);
            tabIcon:loadTexture(getCampSmallIconPath(campSortRule[i]));
            tabIcon:setColor(blendColor);
            tabImage:setColor(blendColor);
        end

        tabNode:addChild(child)
        table.insert(tabNode.rows, child)
    end

    for i = 1, #tabNode.rows do
        local tab = tabNode.rows[i];
        tab:setPositionY(tab:getPositionY() + 100);
    end

    performWithDelay(self, function() self:playTabEffect(); end, 0.2);
end

-- 页签动画效果
function UISkyCityTowerBonus:playTabEffect()
    local tabNode = findChildByName(self.node, "CT/tab");
    -- 带窗口动画播放结束后，页签从上面往下掉
    for i = 1, #tabNode.rows do
        local tab = tabNode.rows[i];
        local pos = cc.p(tab:getPosition());
        local delay = cc.DelayTime:create(0.15 * (i - 1));
        local moveDown = cc.MoveTo:create(0.15, cc.p(pos.x, pos.y - 100 - 5));
        local moveBack = cc.MoveTo:create(0.15, cc.p(pos.x, pos.y - 100));
        local action = cc.Sequence:create(delay, moveDown, moveBack);
        tab:runAction(action);
    end
end

-- 注册标签页点击回调
function UISkyCityTowerBonus:registerTabTouchEvent(node)
    -- 节点
    local tabImage = node:getChildByName("tab");
    local tabLight = node:getChildByName("light");
    local tabIcon = node:getChildByName("icon");
    local tabNode = findChildByName(self.node, "CT/tab");

    -- 置灰颜色
    local blendColor = TextStyleM.TEXT_COLOR_BLEND;
    local normalColor = TextStyleM.TEXT_COLOR_NORMAL;

    local function onClick(sender, eventType)
        -- 点击时的回调
        if eventType == ccui.TouchEventType.ended then
            AudioM.playFx("button_click");
            -- 去除其它高亮
            for i = 1, #tabNode.rows do
                tabNode.rows[i]:getChildByName("light"):setVisible(false);
                tabNode.rows[i]:getChildByName("tab"):setColor(blendColor);
                tabNode.rows[i]:getChildByName("icon"):setColor(blendColor);
            end
            -- 设置本身高亮
            tabLight:setVisible(true);
            tabImage:setColor(normalColor);
            tabIcon:setColor(normalColor);

            -- 设置当前阵营ID
            self.camp = campSortRule[node.index];

            -- 重绘
            self:init();

            -- 重绘
            self:redraw();
        end
    end

    tabImage:addTouchEventListener(onClick);
end